import { createSlice } from '@reduxjs/toolkit'

function generateRandomString(): string {
  const len = Math.floor(Math.random() * 5 + 4)
  const characters =
    'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'
  let result = ''
  for (let i = 0; i < len; i++) {
    const randomIndex = Math.floor(Math.random() * characters.length)
    result += characters[randomIndex]
  }
  return result
}

const codeSlice = createSlice({
  name: 'create',
  initialState: {
    title: '代码片段',
    isShow: false,
    isOpen: true,
    password: generateRandomString(),
    currentTime: '',
    endTime: '永久有效',
    codeNum: 1,
    label: []
  },
  reducers: {
    setIsShow(state, action) {
      state.isShow = action.payload
    },
    setIsOpen(state, action) {
      state.isOpen = action.payload
    },
    setPassword(state, action) {
      state.password = action.payload
    },
    setTitle(state, action) {
      state.title = action.payload
    },
    setCurrentTime(state, action) {
      state.currentTime = action.payload
    },
    setEndTime(state, action) {
      state.endTime = action.payload
    },
    setCodeNum(state, action) {
      state.codeNum = action.payload
    },
    setLabel(state, action) {
      state.label = action.payload
    },
    resetStateCreate(state) {
      state.title = '代码片段'
      state.isShow = false
      state.isOpen = true
      state.password = generateRandomString()
      state.currentTime = ''
      state.endTime = '永久有效'
      state.codeNum = 1
      state.label = []
    }
  }
})

export const {
  setIsShow,
  setIsOpen,
  setPassword,
  setTitle,
  setCurrentTime,
  setEndTime,
  setCodeNum,
  setLabel,
  resetStateCreate
} = codeSlice.actions

export default codeSlice.reducer
